<template>
  <div
    class="menu-item"
    :style="style"
    :class="{ active: active }"
    @click="handleClick"
    ref="menuItem"
  >
    <div class="content" :style="style">
      <div class="svg">
        <component :is="svg" :active="active" :transiton="0.3" />
        <slot></slot>
      </div>
      <span class="text" :style="style">{{ text }}</span>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'x-menu-item',
    props: {
      svg: {
        default: null,
      },
      text: {
        type: String,
        default: '',
      },
      transiton: {
        type: Number,
        default: 0.3,
      },
      label: {
        default: NaN,
      },
    },
    data() {
      return {
        // 用于标识当前菜单项的唯一标识
        activeLabel: undefined,
        style: {
          transition: `all ${this.transiton}s ease-in-out`,
        },
      }
    },
    computed: {
      // 用于标识当前菜单项是否被选中
      active() {
        // 用于标识当前菜单项是否被选中
        return this.label === this.activeLabel
      },
    },
    methods: {
      // 处理点击事件
      handleClick() {
        this.$xbus.$emit('x-menu-item/active', this.label)
      },
      updateActiveLabel(label) {
        this.activeLabel = label
      },
    },
    created() {
      // 同步父组件的value值
      this.$xbus.$on('x-menu/change', this.updateActiveLabel)
      // 通知父组件当前菜单项已挂载
      this.$xbus.$emit('x-menu-item/mounted', this.label)
    },
    beforeDestroy() {
      // 销毁时移除监听
      this.$xbus.$off('x-menu/change', this.updateActiveLabel)
    },
  }
</script>

<style lang="scss" scoped>
  .menu-item {
    width: 200px;
    height: 44px;
    margin-top: 4px;
    transition: all 0.3s ease;
    // background-color: pink;

    &:hover .content {
      background: #f4f9fd;
    }

    &.active {
      &:hover .content {
        background: transparent !important;
      }
      background: transparent !important;
      .text {
        color: rgba(63, 140, 255, 1);
      }
    }
  }

  .content {
    display: flex;
    align-items: center;
    width: 172px;
    height: 44px;
    margin-left: 15px;
    border-radius: 10px;
    background: transparent;
    cursor: pointer;

    .svg {
      width: 20px;
      height: 20px;
      margin-left: 11px;
    }
    .text {
      font-size: 16px;
      font-weight: 400;
      letter-spacing: 0px;
      line-height: 24px;
      color: rgba(63, 140, 255, 1);
      text-align: left;
      vertical-align: middle;
      margin-left: 16px;
      color: rgba(113, 128, 150, 1);
    }
  }
</style>
